import { HTTP } from './http.js'
import api from '../utils/api.js'

let http = new HTTP()

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// function formatNumber(m) {
//   // 添 0
//   return m < 10 ? '0' + m : m
// }

/*函数节流*/
function throttle(fn, interval) {
    var enterTime = 0; //触发的时间
    var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
    return function () {
        var context = this;
        var backTime = new Date(); //第一次函数return即触发的时间
        if (backTime - enterTime > gapTime) {
            fn.call(context, arguments);
            enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
        }
    };
}

/*函数防抖*/
function debounce(fn, interval) {
    var timer;
    var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
    return function () {
        clearTimeout(timer);
        var context = this;
        var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
        timer = setTimeout(function () {
            fn.call(context, args);
        }, gapTime);
    };
}

/*CNY除以100*/ //保留2位 待
function divideByHundred(num) {
    let floatVal = parseFloat(num);
    if (isNaN(floatVal)) {
        return false;
    }
    floatVal = num / 100;
    // console.log('floatVal', floatVal)
    return floatVal
}
function showMsg(message) {
    wx.showToast({
        title: message,
        icon: 'none',
        duration: 1500
    });
}
function showLoading(message) {
    if (wx.showLoading) {
        // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
        wx.showLoading({
            title: message,
            mask: true
        });
    } else {
        // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
        wx.showToast({
            title: message,
            icon: 'loading',
            mask: true,
            duration: 20000
        });
    }
}

function hideLoading() {
    if (wx.hideLoading) {
        // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
        wx.hideLoading();
    } else {
        wx.hideToast();
    }
}
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

    return Y + M + D + h + m + s;

}

//提交订单后，每次 都要 获取菜篮列表，更新菜篮图标的值
function refreshShopCarBadge() {
    let tabBarIndex = 3;
    http.request({
        url: api.shoppingCartList,
        data: {
            user_id: wx.getStorageSync("user_id"),
        },
        success: (res) => {
            if (res.code == 1002) {
                return false
            }

            if (res.code == 404) {
                wx.removeTabBarBadge({
                    index: tabBarIndex,
                })
            } else {
                var list = res.data.data
                let totalNum = 0;

                list.forEach(item => {
                    return totalNum += Number(item.num)
                });
                if (totalNum == 0) {
                    wx.removeTabBarBadge({
                        index: tabBarIndex,
                    })
                } else if (totalNum > 99) {
                    wx.setTabBarBadge({
                        index: tabBarIndex,
                        text: "99+"
                    })
                } else {
                    wx.setTabBarBadge({
                        index: tabBarIndex,
                        text: totalNum.toString(),
                    })
                }
            }
        }
    })
}
// 获取今天 明天 后天 日期
function getDateStr(dayCount) {
    if (null == dayCount) {
        dayCount = 0;
    }
    var dd = new Date();
    dd.setDate(dd.getDate() + dayCount); //设置日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
}



//计算两点位置距离
function getDistance(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    /*if (distance > 1000){
      distance = Math.round(distance / 1000);
    }*/

    return distance;
}
/*
  util.getInfo(url, 'POST',data).then((res)=>{
    
  })
*/
function getInfo(url, method, data, loadding = true) {
    return new Promise((resolve, reject) => {
        if (loadding) {
            wx.showLoading({
                title: '加载中...',
            })
        }
        http.request({
            url: url,
            method: method,
            data: data,
            success: res => {
                if (res.msg && res.error_code) {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 1500
                    });
                    return;
                } else if (res.code == 400 && res.message) {
                    wx.showToast({
                        title: res.message,
                        icon: 'none',
                        duration: 1500
                    });
                    return;
                }

                if (res.code == 200) {
                    resolve(res.data);
                }
                if (loadding) {
                    wx.hideLoading()
                }

            },
            fail: (res) => {
                console.log('error', res)
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    })
}

function countdown(dt) {
    let expired_at = 0,
        now = parseInt((new Date()).getTime() / 1000);

    if (typeof dt == 'string') {
        expired_at = parseInt((new Date(dt.replace(/-/g, '/'))).getTime() / 1000);
    } else if (typeof dt == 'number') {
        expired_at = parseInt(dt);
    } else {
        expired_at = parseInt((new Date()).getTime() / 1000)
    }

    // 时间差
    let seconds = expired_at - now,
        obj = { day: 0, hour: 0, min: 0, seconds: 0 }

    if (seconds >= 0) {
        // obj.day = Math.floor(seconds / 86400);
        // seconds -= obj.day * 86400;
        obj.hour = Math.floor(seconds / 3600);
        seconds -= obj.hour * 3600;
        obj.min = Math.floor(seconds / 60);
        seconds -= obj.min * 60;
        obj.seconds = seconds;
    }
    return obj;
}

function countdownTimer(dt) {
    let timerObject = countdown(dt);
    return `${timerObject.hour}:${timerObject.min}:${timerObject.seconds}`
}

function fenToYuan(fen) {
    let fenInt = parseInt(fen)
    let yuanFloat = fenInt / 100
    return yuanFloat.toFixed(2).toString()
}

function yuanToFen(yuan) {
    let yuanFloat = parseFloat(yuan)
    let fenInt = Math.floor(yuanFloat * 100)
    return fenInt.toString()
}

function percentage(numerator, denominator) {
    let result = parseInt(numerator * 100 / denominator);
    if (result > 100) {
        return 100;
    } else {
        return Math.abs(result);
    }
}

module.exports = {
    formatTime: formatTime,
    throttle,
    debounce,
    divideByHundred,
    showLoading,
    hideLoading,
    refreshShopCarBadge,
    formatNumber,
    getDistance,
    getDateStr,
    getInfo,
    showMsg,
    timestampToTime,
    countdown,
    countdownTimer,
    fenToYuan,
    yuanToFen,
    percentage
}